<template>
    <view class="container">
        <!-- 自定义导航栏 -->
        <custom-navbar :showTitle="false" :title="postData.title" :isCoverNav="true" backgroundColor="#ffffff" textColor="#000000" :showBack="true"></custom-navbar>
        <!-- 轮播图区域 -->
        <view class="swiper-section">
            <swiper class="swiper" :autoplay="swiperAutoplay" :interval="3000" :duration="500" :indicator-dots="postData.image && postData.image.length > 1" indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#ffffff">
                <swiper-item v-for="(media, index) in postData.image" :key="index">
                    <view class="media-item">
                        <image v-if="media.type === 'image'" :src="media.url" class="media-image" mode="aspectFill" @error="onImageError" />
                        <video v-else-if="media.type === 'video'" :src="media.url" class="media-video" controls @play="onVideoPlay" @pause="onVideoPause" @ended="onVideoEnded" />
                    </view>
                </swiper-item>
            </swiper>
        </view>

        <!-- 帖子内容区域 -->
        <view class="post-content-section">
            <view class="post-header">
                <view class="user-info">
                    <image v-if="postData?.user_info?.avatar" :src="postData.user_info.avatar" class="user-avatar" mode="aspectFill" />
                    <view class="user-details">
                        <text class="username">{{ postData?.user_info?.nickname || '匿名用户' }}</text>
                        <text class="post-time">{{ postData?.user_info?.create_time }}</text>
                    </view>
                </view>
            </view>

            <view class="post-text">
                <view class="post-text-title">{{ postData.title }}</view>
                <text>{{ postData.content }}</text>
            </view>
        </view>

        <!-- 评论区域 -->
        <view class="comments-section" :class="{ 'sticky': isCommentsSticky }">
            <view class="comments-header">
                <text class="comments-title">评论 ({{ comments.length }})</text>
            </view>

            <scroll-view class="comments-scroll" scroll-y @scrolltolower="loadMoreComments" :style="{ height: commentsHeight }">
                <view class="comments-list">
                    <view v-for="comment in comments" :key="comment.id" class="comment-box" @click="replyToComment(comment)">
                        <view class="comment-item">
                            <image v-if="comment?.user_info?.avatar" :src="comment.user_info.avatar" class="comment-avatar" mode="aspectFill" />
                            <view class="comment-content">
                                <view class="comment-header">
                                    <text class="comment-username">{{ comment?.user_info?.nickname || '匿名用户' }}</text>
                                    <text class="comment-time">{{ comment?.user_info?.create_time }}</text>
                                </view>
                                <text class="comment-text">{{ comment.content }}</text>
                            </view>
                            <view class="reply-btn" @click.stop="replyToComment(comment)">
                                <text class="reply-text">回复</text>
                            </view>
                        </view>
                        
                        <!-- 回复评论 -->
                        <view v-if="comment.reply_list && comment.reply_list.length > 0" class="reply-list">
                            <view v-for="reply in comment.reply_list" :key="reply.id" class="reply-item" @click.stop="replyToReply(comment, reply)">
                                <image v-if="reply?.user_info?.avatar" :src="reply.user_info.avatar" class="reply-avatar" mode="aspectFill" />
                                <view class="reply-content">
                                    <view class="reply-header">
                                        <text class="reply-username">{{ reply?.user_info?.nickname || '匿名用户' }}</text>
                                        <text class="reply-time">{{ reply?.user_info?.create_time }}</text>
                                    </view>
                                    <view class="reply-text-container">
                                        <text v-if="reply.reply_id !== 0" class="reply-text">
                                            回复 @{{ getReplyTargetName(comment.reply_list, reply.reply_id) }}: {{ reply.content }}
                                        </text>
                                        <text v-else class="reply-text">
                                            {{ reply.content }}
                                        </text>
                                    </view>
                                </view>
                                <view class="reply-btn-small" @click.stop="replyToReply(comment, reply)">
                                    <text class="reply-text-small">回复</text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view v-if="loadingMore" class="loading-more">
                        <text class="loading-text">加载中...</text>
                    </view>
                    <view v-if="noMoreComments" class="no-more">
                        <text class="no-more-text">没有更多评论了</text>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!-- 底部固定输入栏 -->
        <view class="bottom-bar">
            <view class="input-container" @click="showCommentModal">
                <text class="input-placeholder">写评论...</text>
            </view>
            <view class="like-container" @click="toggleLike">
                <text class="like-icon" :class="{ 'liked': isLiked }">♥</text>
                <text class="like-count">{{ likeCount }}</text>
            </view>
        </view>

        <!-- 评论弹窗 -->
        <view v-if="showModal" class="modal-overlay" @click="hideCommentModal">
            <view class="comment-modal" @click.stop>
                <view class="modal-header">
                    <text class="modal-title">写评论</text>
                    <text class="modal-close" @click="hideCommentModal">×</text>
                </view>
                <textarea v-model="commentText" class="comment-input" :placeholder="placeholderText" maxlength="500" auto-focus />
                <view class="modal-footer">
                    <text class="char-count">{{ commentText.length }}/500</text>
                    <!-- 这里使用uview-plus 的按钮 -->
                    <u-button type="primary" shape="circle" class="submit-btn" @click="submitComment" :disabled="!commentText.trim()">发布</u-button>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref, onMounted, nextTick } from 'vue'
import { postDetailFun, postCommentListFun, postAddFun, postCommentReplyAddFun, postCommentAgreeFun, postCommentAddFun } from '@/api/port.js'
import customNavbar from '../../components/custom-navbar/index.vue';


interface ShareResult {
    title?: string
    path?: string
}






// 响应式数据
const postData = ref<any>({})

const comments = ref<any[]>([])
const isLiked = ref(false)
const likeCount = ref(0)
const showModal = ref(false)
const commentText = ref('')

// 轮播控制
const swiperAutoplay = ref(true)

// 粘性布局相关
const isCommentsSticky = ref(false)
const commentsHeight = ref('400rpx')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const loadingMore = ref(false)
const noMoreComments = ref(false)

// 页面参数
const postId = ref('')


// 回复评论相关
const placeholderText = ref('说点什么吧...')
const is_reply = ref(false)
const replyInfo = ref<any>({})

// 加载帖子详情
const loadPostDetail = async (): Promise<void> => {
    try {
        const res = await postDetailFun({ id: postId.value })
        if (res.code === 1) {
            console.log('帖子详情',res.data)
            const data = res.data
            postData.value = data
            
            isLiked.value = data.is_liked || false
            likeCount.value = data.like_count || 0
        }
    } catch (error) {
        console.error('加载帖子详情失败:', error)
        uni.showToast({
            title: '加载失败',
            icon: 'none'
        })
    }
}

// 加载评论列表
const loadComments = async (page: number = 1): Promise<void> => {
    if (loadingMore.value) return
    
    loadingMore.value = true
    try {
        const res = await postCommentListFun({
            post_id: postId.value,
            page: page,
            page_size: pageSize.value
        })
        
        if (res.code === 1) {
            const newComments = res.data.list || []
            if (page === 1) {
                comments.value = newComments
            } else {
                comments.value.push(...newComments)
            }
            
            // 判断是否还有更多数据
            if (newComments.length < pageSize.value) {
                noMoreComments.value = true
            }
        }
    } catch (error) {
        console.error('加载评论失败:', error)
    } finally {
        loadingMore.value = false
    }
}

// 加载更多评论
const loadMoreComments = (): void => {
    if (!noMoreComments.value && !loadingMore.value) {
        currentPage.value++
        loadComments(currentPage.value)
    }
}

// 生命周期函数--监听页面初次渲染完成
const onPageReady = (): void => {
    // 页面渲染完成逻辑
    setupStickyComments()
}


// 设置粘性评论布局
const setupStickyComments = (): void => {
    nextTick(() => {
        const query = uni.createSelectorQuery()
        query.select('.comments-section').boundingClientRect((rect) => {
            if (rect) {
                const windowHeight = uni.getSystemInfoSync().windowHeight
                const stickyPosition = windowHeight * 0.3 // 30vh位置
                
                // 监听页面滚动
                uni.onPageScroll((e) => {
                    const scrollTop = e.scrollTop
                    const commentsTop = rect.top + scrollTop
                    
                    if (commentsTop <= stickyPosition) {
                        isCommentsSticky.value = true
                        commentsHeight.value = `${windowHeight - stickyPosition - 120}px` // 减去底部输入栏高度
                    } else {
                        isCommentsSticky.value = false
                        commentsHeight.value = '400rpx'
                    }
                })
            }
        }).exec()
    })
}

// 视频播放控制
const onVideoPlay = (): void => {
    swiperAutoplay.value = false
}

const onVideoPause = (): void => {
    swiperAutoplay.value = true
}

const onVideoEnded = (): void => {
    swiperAutoplay.value = true
}


// 用户点击右上角分享
const onPageShareAppMessage = (): ShareResult => {
    return {
        title: postData.value.content.substring(0, 20) + '...',
        path: `/subpackage/salesDetail/salesDetail?id=${postData.value.id}`
    }
}

// 交互函数
const toggleLike = (): void => {
    isLiked.value = !isLiked.value
    likeCount.value += isLiked.value ? 1 : -1
    postCommentAgreeFun({
        id: postData.value.id,
    }).then((res) => {
        if (res.code === 1) {
            uni.showToast({
                title: '操作成功',
                icon: 'success'
            })
        }else{
            uni.showToast({
                title: res.msg,
                icon: 'none'
            })
        }
    })
}

const showCommentModal = (): void => {
    showModal.value = true
}

const hideCommentModal = (): void => {
    showModal.value = false
    commentText.value = ''
    placeholderText.value = '说点什么吧...'
    is_reply.value = false
    replyInfo.value = {}
}

const submitComment = (): void => {
    if (!commentText.value.trim()) return

    if(is_reply.value){
        // 回复评论
        const isReplyToReply = replyInfo.value.reply_target // 是否回复二级评论
        const replyParams = {
            reply_id: isReplyToReply ? replyInfo.value.reply_target.id : 0,
            reply_user_id: isReplyToReply ? replyInfo.value.reply_target.user_info.id : replyInfo.value.user_info.id,
            post_id: postId.value,
            content: commentText.value.trim(),
            comment_id: replyInfo.value.id
        }
        
        postCommentReplyAddFun(replyParams).then(res=>{
            if (res.code === 1) {
                loadComments(1)
                uni.showToast({
                    title: '回复成功',
                    icon: 'success'
                })
            }else{
                uni.showToast({
                    title: res.msg,
                    icon: 'none'
                })
            }
        })
    }else{
        // 提交评论
        postCommentAddFun({
            post_id: postId.value,
            content: commentText.value.trim()
        }).then((res) => {
            if (res.code === 1) {
                loadComments(1)
                uni.showToast({
                    title: '评论成功',
                    icon: 'success'
                })
            }else{
                uni.showToast({
                    title: res.msg,
                    icon: 'none'
                })
            }
        })
    }
    hideCommentModal()
    
}

// 回复评论功能
const replyToComment = (comment: any): void => {
    console.log('回复评论:', comment)
    replyInfo.value = comment
    // 设置回复的占位符文本
    const replyPlaceholder = `回复 @${comment?.user_info?.nickname || '匿名用户'}:`
    placeholderText.value = replyPlaceholder
    is_reply.value = true
    // 显示评论弹窗
    showModal.value = true
    
    // 可以在这里设置一个回复目标，用于后续提交时区分是普通评论还是回复
    // 这里可以添加更多回复逻辑，比如：
    // - 设置回复目标ID
    // - 修改弹窗标题
    // - 预填充@用户名等
    
    // 示例：修改弹窗的占位符
    // nextTick(() => {
    //     const textarea = document.querySelector('.comment-input') as HTMLTextAreaElement
    //     if (textarea) {
    //         textarea.placeholder = replyPlaceholder
    //     }
    // })
    
    uni.showToast({
        title: `准备回复 ${comment.user_info.nickname}`,
        icon: 'none',
        duration: 1500
    })
}

// 根据reply_id获取回复目标用户名
const getReplyTargetName = (replyList: any[], replyId: number): string => {
    const targetReply = replyList.find(reply => reply.id === replyId)
    return targetReply?.user_info?.nickname || '匿名用户'
}

// 回复二级评论功能
const replyToReply = (comment: any, reply: any): void => {
    console.log('回复二级评论:', reply)
    replyInfo.value = {
        ...comment,
        reply_target: reply
    }
    
    // 设置回复的占位符文本
    const replyPlaceholder = `回复 @${reply?.user_info?.nickname || '匿名用户'}:`
    placeholderText.value = replyPlaceholder
    is_reply.value = true
    
    // 显示评论弹窗
    showModal.value = true
    
    uni.showToast({
        title: `准备回复 ${reply.user_info.nickname}`,
        icon: 'none',
        duration: 1500
    })
}

const onImageError = (event: any): void => {
    console.log('图片加载失败')
    // 可以设置默认图片
    const target = event.target
    if (target) {
        target.src = '/static/images/home_none.png'
    }
}
onLoad((options)=>{
	if (options.id) {
		postId.value = options.id
		loadPostDetail()
		loadComments()
	}
})

</script>
<style scoped>
.container {
    min-height: 100vh;
    background-color: #f8f9fa;
    padding-bottom: 120rpx;
    /* 为底部固定栏留出空间 */
}

/* 轮播图区域 */
.swiper-section {
    width: 100%;
    height: 500rpx;
    position: relative;
}

.swiper {
    width: 100%;
    height: 100%;
}

.media-item {
    width: 100%;
    height: 100%;
    position: relative;
}

.media-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.media-video {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

/* 帖子内容区域 */
.post-content-section {
    background-color: #ffffff;
    padding: 32rpx;
    margin-bottom: 20rpx;
}

.post-header {
    margin-bottom: 24rpx;
}

.user-info {
    display: flex;
    align-items: center;
}

.user-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 24rpx;
}

.user-details {
    flex: 1;
}

.username {
    display: block;
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 8rpx;
}

.post-time {
    font-size: 24rpx;
    color: #999999;
}

.post-text {
    font-size: 30rpx;
    line-height: 1.6;
    color: #333333;
}
.post-text-title{
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 24rpx;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 评论区域 */
.comments-section {
    background-color: #ffffff;
    padding: 32rpx;
    transition: all 0.3s ease;
}

.comments-section.sticky {
    position: fixed;
    top: 30vh;
    left: 0;
    right: 0;
    bottom: 120rpx;
    z-index: 99;
    border-top: 1rpx solid #f0f0f0;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.comments-header {
    margin-bottom: 32rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.comments-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
}

.comments-scroll {
    width: 100%;
}

.comments-list {
    /* 评论列表样式 */
}
.comment-box{
    margin-bottom: 32rpx;
    padding-bottom: 32rpx;
}
.comment-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    
    border-bottom: 1rpx solid #f8f9fa;
    transition: background-color 0.2s ease;
}

.comment-item:hover {
    /* background-color: #f8f9fa; */
}

.comment-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.comment-avatar {
    width: 64rpx;
    height: 64rpx;
    border-radius: 32rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
}

.comment-content {
    flex: 1;
}

.comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 12rpx;
}

.comment-username {
    font-size: 28rpx;
    font-weight: 500;
    color: #333333;
    margin-right: 16rpx;
}

.comment-time {
    font-size: 24rpx;
    color: #999999;
}

.reply-btn {
    /* padding: 8rpx 16rpx; */
    /* background-color: #f0f0f0; */
    /* border-radius: 20rpx; */
    margin-left: 16rpx;
    /* flex-shrink: 0; */
    /* transition: all 0.2s ease; */
}

.reply-btn:hover {
    /* background-color: #e0e0e0; */
}

.reply-text {
    font-size: 24rpx;
    color: #666666;
}

.comment-text {
    font-size: 28rpx;
    line-height: 1.5;
    color: #666666;
}

/* 二级评论样式 */
.reply-list {
    margin-top: 24rpx;
    margin-left: 84rpx; /* 头像宽度 + 间距 */
    padding-left: 24rpx;
    border-left: 2rpx solid #f0f0f0;
}

.reply-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20rpx;
    padding: 16rpx;
    /* background-color: #f8f9fa; */
    border-radius: 12rpx;
    transition: background-color 0.2s ease;
}

.reply-item:hover {
    /* background-color: #f0f0f0; */
}

.reply-item:last-child {
    margin-bottom: 0;
}

.reply-avatar {
    width: 48rpx;
    height: 48rpx;
    border-radius: 24rpx;
    margin-right: 16rpx;
    flex-shrink: 0;
}

.reply-content {
    flex: 1;
}

.reply-header {
    display: flex;
    align-items: center;
    margin-bottom: 8rpx;
}

.reply-username {
    font-size: 24rpx;
    font-weight: 500;
    color: #333333;
    margin-right: 12rpx;
}

.reply-time {
    font-size: 20rpx;
    color: #999999;
}

.reply-text-container {
    margin-top: 4rpx;
}

.reply-text {
    font-size: 24rpx;
    line-height: 1.4;
    color: #007aff;
}

.reply-btn-small {
    /* padding: 4rpx 12rpx; */
    /* background-color: #e0e0e0; */
    /* border-radius: 16rpx; */
    margin-left: 12rpx;
    /* flex-shrink: 0; */
    /* transition: all 0.2s ease; */
}

.reply-btn-small:hover {
    /* background-color: #d0d0d0; */
}

.reply-text-small {
    font-size: 24rpx;
    color: #007aff;
}

/* 底部固定栏 */
.bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    background-color: #ffffff;
    border-top: 1rpx solid #f0f0f0;
    display: flex;
    align-items: center;
    padding: 0 32rpx;
    z-index: 100;
}

.input-container {
    flex: 1;
    height: 72rpx;
    background-color: #f8f9fa;
    border-radius: 36rpx;
    display: flex;
    align-items: center;
    padding: 0 24rpx;
    margin-right: 24rpx;
}

.input-placeholder {
    font-size: 28rpx;
    color: #999999;
}

.like-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 8rpx 16rpx;
}

.like-icon {
    font-size: 48rpx;
    color: #cccccc;
    transition: all 0.3s ease;
}

.like-icon.liked {
    color: #ff4757;
    transform: scale(1.1);
}

.like-count {
    font-size: 20rpx;
    color: #999999;
    margin-top: 4rpx;
}

/* 评论弹窗 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: flex-end;
    z-index: 1000;
}

.comment-modal {
    width: 100%;
    background-color: #ffffff;
    border-radius: 24rpx 24rpx 0 0;
    padding: 32rpx;
    animation: slideUp 0.3s ease;
}

@keyframes slideUp {
    from {
        transform: translateY(100%);
    }

    to {
        transform: translateY(0);
    }
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
}

.modal-close {
    font-size: 48rpx;
    color: #999999;
    line-height: 1;
}

.comment-input {
    width: 100%;
    min-height: 200rpx;
    padding: 24rpx;
    border: 1rpx solid #f0f0f0;
    border-radius: 12rpx;
    font-size: 28rpx;
    line-height: 1.5;
    background-color: #f8f9fa;
    margin-bottom: 24rpx;
    resize: none;
}

.modal-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.char-count {
    font-size: 24rpx;
    color: #999999;
}

.submit-btn {
    background-color: #007aff;
    color: #ffffff;
    border: none;
    border-radius: 24rpx;
    padding: 16rpx 32rpx;
    font-size: 28rpx;
    font-weight: 500;
    width: 240rpx !important;
    margin: 0 !important;
    box-sizing: border-box;
}

.submit-btn:disabled {
    background-color: #cccccc;
    color: #999999;
}

/* 加载状态 */
.loading-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 32rpx;
}

.loading-text {
    font-size: 28rpx;
    color: #999999;
}

.no-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 32rpx;
}

.no-more-text {
    font-size: 24rpx;
    color: #cccccc;
}
</style>
